<?php
/*
Bach
2016-12-06
v0.02

/login/index主界面

/login/account_check

/login/qrcode
/login/qrcode_create
/login/qrcode_check

/login/scan
/login/scan_confirm

/login/email_send
/login/email_check

/login/sms_send
/login/sms_check

/login/wechat_base
/login/wechat_user_info

/login/out

*/
namespace app\hongyanche\Controller;

class Login{
    private $userId;
    public function __construct(){
        //获取user_id
        if (is_null($this->userId)) {
            $user_id = model('user');
            $userId = $this->userId = $user_id->getUserId();
        } else {
            $userId = $this->userId;
        }
        if (!$userId) {
            return;
        }
    }
	private function vcode(){
		$vcode_times = (int)session('vcode_times');
		if($vcode_times<2){
			session('vcode_times',$vcode_times+1);
			return true;
		}
		if(session('vcode')){
			return true;
		}
		$vcode = input("vcode");
		if(!$vcode){
			return false;
		}
		$res = vcodeCheck($vcode);
		if(!$res['state']){
			return false;
		}
		session('vcode',1);
		return true;
	}

	//账户登陆
	//账户登陆
	//账户登陆
	//账户登陆检查
	
	public function account_check(){//接口
		$vcode = $this->vcode();
		if(!$vcode) return json(["errormsg"=>"图形码错误"]);
		$account 	= input('account');
        $rs= preg_match(
            "/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/",
            $account
        );
        if($rs){
            return json(['state'=>0,'errormsg'=>'账号不存在']);
        }
		$password	= input('password');
		$auto 	= (int)input('auto');
        //检查成功
		$data = array(
			'account' 	=> $account,
			'password'	=> $password,
			'auto'		=> $auto,
			);
		$res = model('user')->login( $demand = "account" , $data );
		if(isset($res['state']) && $res['state']){
			session('vcode',null);
			session('vcode_times',null);
		}
		//暂时解决跨域问题
        $res['data']['info']['session'] = session_id();
		return json($res);
	}

	//微信二维码登陆
	//微信二维码登陆
	//微信二维码登陆
	//二维码生成
	public function qrcode_create(){//接口
		$user = model('User');
		$userInfo = $user->info();
		if( isset($userInfo['data']['openid']) && $userInfo['data']['openid'] ){
			return json(['state'=>0,'errormsg'=>'您已绑定微信,不能重复绑定']);
		}
		$token = model('Token');
		$token = $token->add( $demand = 'login_wechat' );
		if(!$token['state']){
			return json($token);
		}
		$code = $token['data']['code'];
		$remain = $token['data']['remain'];
		//
		$qrcode = array(
			'state' 	=> 1,
			'data' 		=> array(
				'code' => $code,
				'url' =>  $_SERVER['HTTP_HOST']."/login/qrcode_url?code=$code",
				'remain'=>$remain,
				),
			) ;
		return json($qrcode);
	}
	public function qrcode_url(){
		$code = $_GET['code'];
		$url = config("url")."login/scan?code=$code";
		// dump($url);
		$level=5;
		$size=10;
		getQrcode($url);
}

	//二维码检查
	public function qrcode_check(){//接口
		$code = input('code');
		$auto = input('auto');
		$user = model('user');
		$res = $user->login(
			$demand = 'wechat',
			$data=array(
				'code'		=> $code,
				'auto'		=>$auto,
				) 
			);
		return json($res);
	}

	public function scan(){//界面
		if(!isWeixin()){
	        header('Location:/');
	        die();
		}
		$user = model('User');
		$user->wechatAutoLogin();
		$userInfo = $user->info();
		$userInfo = isset($userInfo['data'])?$userInfo['data']:[];
		return view("wechat-scan",["userInfo"=>$userInfo]);
	}
	public function scan_confirm(){//接口 确认登陆
		$code 		= input('code');
	    if(!$code){
	        return json(['state'=>0,'errormsg'=>'need code']);
	    }
		$user_id = model('user')->getUserId();
	    if(!$user_id){
	        return json(['state'=>0,'errormsg'=>'need user_id']);
	    }
	    $data = array('code'=>$code,'content'=>$user_id);
	    $respond = model('token')->respond("login_wechat", $data);
	    if(!$respond['state']){
	    	return json($respond);
	    }
	    session('user',null);
	    cookie('auto', null);
		return json($respond);
		// $respond['data']['code'] = $code;
		// $this->ajaxReturn($respond);
	}

	//邮箱登陆
	//邮箱登陆
	//邮箱登陆
	/* 
	* PHP简单利用token防止表单重复提交 
	*/  

	// 发送邮件
	public function email_send(){//接口
		$vcode = $this->vcode();
		if(!$vcode) return json(["errormsg"=>"vcode error"]);
		$email 	= input('email');
        if(!$this->userId){
            return json(["errormsg"=>"please login"]);
        }
		if(!$email) return json(['errormsg'=>'need email']);
		$auto 	= input('auto');
		//登陆状态
		$user = model('User');
		if($user->logined()){
			$userInfo = $user->info();
			//如果已经绑定了邮箱，
			$emailExist = isset($userInfo['data']['email'])?$userInfo['data']['email']:false;
			if($emailExist){
				//非密码解锁行为，告知无需发送绑定邮箱
				return json(['state'=>0,'errormsg'=>'already has email']);
			}
			//如果已有邮箱账号 则检测 1本账号是否已绑定电话 2目标帐号是否绑定过微信
			$existRes = $user->exist(array('email'=>$email));
			if(isset($existRes['state']) && $existRes['state']){
				$exist_user_id = $existRes['data']['user_id'];
				if(isset($userInfo['data']['tel']) || $user->getInfoById($exist_user_id)['openid']){
					return json(['errormsg'=>'email exist']);
				}
			}
			
		}
		$code = session('login_mail_token');
		if(!$code){
			$token = model('Token');
			$token = $token->add($demand = 'login_email', $data = array('content'=>$email));
			if(!isset( $token['state'] ) || !$token['state']){//生成token失败
				return json($token);
			}
			$code = $token['data']['code'];
			session('login_mail_token',$code);
		}
		//
		$sendmail = model('Email');
		$sendmail = $sendmail->send( 
			$demand = "login",
			$data = array( 
				'code'=>$code,
				'auto'=>$auto?"?auto=1":"",
				'email'=>$email
				)
			) ;
		//var_dump($sendmail);
		if(!isset($sendmail['state']) || !$sendmail['state']){
			return json($sendmail);
		}
		session('vcode',null);
		session('login_mail_token',null);
		return json($sendmail);
	}

	//检查
	public function email_check() {
		//界面
		//if( D('user')->logined() ){
			//$this->redirect($this->home);
		//}
		$code	= input('code');
		$auto	= (int)input('auto');
		//检查成功
		$user = model('User');
		$result = $user->login(
			$demand = 'email' ,
			$data = array(
				'code'=>$code,
				'auto'=>$auto,
				) 
			);
		//echo 'Bach---GET:<BR>';
		//var_dump($_GET);
		//echo '<BR>Bach---DATA:<BR>';
		//var_dump($data);
		if(!isset($result['state'])||!$result['state']){
			return view("email-check-fail",[
				'errormsg'=>$result["errormsg"],
			]);
		}
		return view("email-check-success");
	}

	//手机号码登陆
	//手机号码登陆
	//手机号码登陆
	//发送短信验证码
	public function sms_send(){//接口
        $tel = input("tel");
        if(!$tel){
            return json(['errormsg'=>'请输入手机号码']);
        }
		$vcode = $this->vcode();
		if(!$vcode) return json(["state"=>0,"errormsg"=>"图形码错误"]);
		$user = model('User');
		if($user->logined()){
			$userInfo = $user->info();
			//如果已经绑定了手机
			$telExist = isset($userInfo['data']['tel'])?$userInfo['data']['tel']:false;
			if( $telExist ){
				return json(['state'=>0,"errormsg"=>"already has tel"]);
			}
			//如果已有手机账号 则检测 1本账号是否已绑定邮箱 2目标帐号是否绑定过微信
			$existRes = $user->exist(["tel"=>$tel]);
			if(isset($existRes['state']) && $existRes['state']){
				$exist_user_id = $existRes['data']['user_id'];
				$exist_user = $user->getInfoById($exist_user_id);
				if( (isset($userInfo['email']) && $userInfo['email']) || ( isset($exist_user['openid']) && $exist_user['openid']) ){
					return json(["errormsg"=>'tel exist']);
				}
			}
		}
 		//请求一个邮箱登陆码 $result['data']['code'] = AUFYE$T*I#U*EDF*E#GR*#R
		$code = session("sms_login_token");
 		if(!$code){
			$result = model('Token')->add($demand = 'login_sms', $data = array('content'=>$tel));
			if(!isset($result['state']) || !$result['state']){
				return json($result);
			}
			$code = $result['data']['code'];
			session("sms_login_token",$code);
 		}
		//
		$sendsms = model("Sms")->send( 
			$demand = "login", 
			$data = array( 
				'tel'=>$tel,
				'code'=>$code,
				) 
			) ;
		if(!isset($sendsms['state']) || !$sendsms['state']){
			return json($sendsms);
		}
		session("sms_login_token",null);
		session("vcode",null);
		return json($sendsms);
	}

	//检测验证码
	public function sms_check(){//接口
		$tel 	 = input('tel');
		$code 	 = input('code');
		$auto 	= (int)input('auto');
		$introduce 	= input('introduce');
        $password = input('password');
        $passwordx = input('passwordx');
        $resets = input('resets');
        if(!$password) return json(['errormsg'=>'请输入密码']);
        if(!$passwordx) return json(['errormsg'=>'请确认密码']);
        if($password !=$passwordx){
            return json(['errormsg'=>'两次密码不一致']);
        }
		//检查成功
		$ret = model('User')->login( 
			$demand = 'tel' ,
			$data = array(
				'tel'		=> $tel ,
				'auto'		=> $auto,
				'code'		=> $code,
				) 
			);
        if($ret['state']){
            //获取user_id
            $user = model('User')->info();
            $user_id = $user['data']['user_id'];
            //判断是否是修改密码
            if($resets){
                $time = time();
                $password = md5($password);
                db('user_password')->where("user_id = $user_id and state = 1")->update(['state'=>0,'create_time'=>$time]);
                $insert = [
                    'state'         => 1,
                    'create_time'   => time(),
                    'password'      => $password,
                    'user_id'       => $user_id,
                ];
                $pass = db('user_password')->insert($insert);
                if(!$pass){
                    //注册失败 删除电话
                    session('user',null);
                    db('user_password')->where("user_id = $user_id and create_time = $time")->update(['state'=>1]);
                    return ['state'=>0,'errormsg'=>'修改失败'];
                }
                return json($ret);
            }
            //判断是否有密码
            $passw = db('user_password')->where("user_id = $user_id and state = 1")->find();
            if($passw) {
                //判断是否有手机
                $tel = db('user_tel')->where("user_id = $user_id and state = 1")->find();
                if($tel){
                    session('user',null);
                    return ['state'=>0,'errormsg'=>'该手机已注册,请使用账号密码登录'];
                }else{
                    db('user_password')->where("user_id = $user_id and state = 1")->update(['state'=>0]);
                }
            }
            //加入密码
            $password = md5($password);
            $insert = [
                'state'         => 1,
                'create_time'   => time(),
                'password'      => $password,
                'user_id'       => $user_id,
            ];
            $pass = db('user_password')->insert($insert);
            if(!$pass){
                //注册失败 删除电话
                db('user_tel')->where("tel = $tel")->update(['state'=>0]);
                session('user',null);
                return ['state'=>0,'errormsg'=>'注册失败'];
            }
            if($introduce){
                $introduce = (int)$introduce;
                //判断推荐人是否存在
                $res = db('user')->where("user_id = $introduce and state = 1")->find();
                if($res) {
                    $user = model('User');
                    $info = $user->info();
                    //判断用户是否已经拥有推荐人
                    if (isset($info['state']) && $info['state']) {
                        //添加推荐人
                        $user_id = $info['data']['user_id'];
                        $info = db('user')->where("user_id = $user_id")->field('introduce')->find();
                        if($info) {
                            db('user')->where("user_id = $user_id")->update(['introduce' => $introduce]);
                        }
                    }
                }
            }
        }
		return json($ret);
	}
	//微信
	public function wechat_base(){
		session("login_wechat",1);
		// $_SESSION['wechatLogin'] = 1;
		// $user = D('User');
		model('User')->loginBaseRedirect();
	}
	public function wechat_user_info(){
		session("login_wechat",1);
		// $_SESSION['wechatLogin'] = 1;
		// $user = D('User');
		model('User')->loginUserInfoRedirect();
	}
}